import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from 'axios';
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from '@/components/Loading/fullScreen';
import { ResultData } from '@/api/interface';
import { ResultEnum } from '@/enums/httpEnum';
import { AxiosCanceler } from './helper/axiosCancel';
import { Message } from '@arco-design/web-react';
import store from '@/store';
import locale from './locale';
import { get } from '@/utils/storage';

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
  cancel?: boolean;
}

const getLocale = (key: keyof (typeof locale)['en-US']) => {
  const lang: keyof typeof locale =
    (get('arco-lang') as keyof typeof locale) || 'ar-EG';
  return locale[lang][key];
};

const config = {
  // The default address request address
  baseURL: process.env.REACT_APP_API,
  // timeout
  timeout: ResultEnum.TIMEOUT as number,
  // Credentials are allowed to be carried across domains
  withCredentials: false,
};

const longTimeConfig = {
  // The default address request address
  baseURL: process.env.REACT_APP_API,
  // timeout
  timeout: 999999999,
  // Credentials are allowed to be carried across domains
  withCredentials: false,
};

const axiosCanceler = new AxiosCanceler();

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);

    /**
     * @description request interceptor
     * Client sends request -> [request interceptor] -> server
     * token verification (JWT): Accept the token returned by the server and store it in redux/local storage
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        // cancel request
        config.cancel ?? (config.cancel = true);
        config.cancel && axiosCanceler.addPending(config);
        // request loading
        config.loading && showFullScreenLoading();
        if (config.headers && typeof config.headers.set === 'function') {
          const token = store.getState().token
            ? `Bearer ${store.getState().token}`
            : '';
          config.headers.set('Authorization', token);
        }
        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description response interceptor
     *  The server returns the information -> [intercept unified processing] -> the client JS gets the information
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse & { config: CustomAxiosRequestConfig }) => {
        const { data, config } = response;
        axiosCanceler.removePending(config);
        config.loading && tryHideFullScreenLoading();
        // login failure
        if (data.code == 1023 || data.code == 1001 || data.code == 1020) {
          type ErrorCode = '1001' | '1012' | '1020' | '1023';
          const msg = getLocale(
            `request.error.${data.code}` as `request.error.${ErrorCode}`
          );
          Message.error({
            id: 'request_update',
            content: msg,
          });
          store.dispatch({
            type: 'reset',
          });
          return Promise.reject(data);
        }
        if (data.code && data.code !== 200) {
          Message.error({ id: 'request_update', content: data.msg });

          return Promise.reject(data);
        }
        return data;
      },
      (error: AxiosError & { config: CustomAxiosRequestConfig }) => {
        const { message: msg, config } = error;
        config.loading && tryHideFullScreenLoading();
        if (error.message.indexOf('timeout') !== -1) {
          Message.error({
            id: 'request_update',
            content: getLocale(`request.error.timeout`),
          });
        }

        if (error.message.indexOf('Network Error') !== -1) {
          Message.error({
            id: 'request_update',
            content: getLocale(`request.error.networkErr`),
          });
        }
        return Promise.reject(msg || 'Error');
      }
    );
  }

  /**
   * @description Common request method encapsulation
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(
    url: string,
    params?: object | string,
    _object = {}
  ): Promise<ResultData<T>> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: 'blob' });
  }

  downloadGet(url: string, _object = {}): Promise<BlobPart> {
    return this.service.get(url, { ..._object, responseType: 'blob' });
  }
}

export const http = new RequestHttp(config);
export const longTimeHttp = new RequestHttp(longTimeConfig);
